package com.group7.mall.websocket;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;  
import java.util.concurrent.locks.ReentrantLock;  
  
public class UserSessionStatus {
    private static final Lock lock = new ReentrantLock();
    private static final Condition chatLoaded = lock.newCondition();
    private static Map<String, Boolean> loadingStatuses = new ConcurrentHashMap<>();
  
    public static void setLoadingStatus(String userId, boolean status) {
        lock.lock();
        if (status) {
            System.out.println("用户 " + userId + " 正在加载聊天记录，上锁");
        } else {
            System.out.println("用户 " + userId + " 已经加载好聊天记录，上锁");
        }
        try {  
            loadingStatuses.put(userId, status);
            System.out.println("设置用户状态为" + status);
            if (!status) {  
                // 如果加载状态变为false，通知等待的线程（可能是onMessage方法中的线程）  
                chatLoaded.signalAll();  
            }  
        } finally {  
            lock.unlock();
            System.out.println("解锁");
        }  
    }  
  
    public static boolean isLoading(String userId) {
        // 第二个参数是一个默认值，当Map中不存在与第一个参数对应的键时，会返回这个默认值。
        return loadingStatuses.getOrDefault(userId, false);  
    }  
  
    public static void waitForChatLoaded(String userId) throws InterruptedException {
        lock.lock();
        System.out.println("检查用户 " + userId + " 是否正在加载聊天记录，上锁");
        try {
            // 原先是true
            if (loadingStatuses.getOrDefault(userId, false)) {
                System.out.println("该用户正在加载聊天记录，发送方需要等待一下");
            } else {
                System.out.println("该用户没有加载聊天记录");
            }
            while (loadingStatuses.getOrDefault(userId, false)) {
                // 如果用户还在加载聊天记录，则等待  
                chatLoaded.await();  
            }  
        } finally {
            System.out.println("检查用户 " + userId + " 已完成，解锁");
            lock.unlock();  
        }  
    }  
}  